# coding: utf-8
import time
import datetime
import json
import requests
import UploadSurvey as us
# from fralog.kafka_logger import KafkaLogger
from settings import *
from flask import request, make_response, Response
from fralog.FraLog import Fralog
import pypinyin
from pypinyin import lazy_pinyin, Style

import globalsettings
from globalsettings import CUR_MODE

if CUR_MODE == 'dev':
    from globalsettings_dev import *
else:
    from globalsettings_prod import *

log = Fralog().getFileLog()


def feature2ocean(data, mode='feature'):
    dic = {}
    dic['mode'] = mode
    dic['data'] = data
    url = 'http://%s:%s/ocean?jstr=%s' % (OCEAN_IP, OCEAN_PORT, json.dumps(dic))
    q = requests.get(url=url).content.decode()
    return json.loads(q)


def get_hr_feature(dic):
    """
    BOLE获取HR特征的接口
    :param dic: 
    :return: 
    """
    url = 'http://%s:%d/application/feature?jstr=%s' % (OCEAN_IP, OCEAN_PORT, json.dumps(dic))
    log.info('后台接口: %s' % url)
    q = requests.get(url=url).content.decode()
    return q


def get_zhuoyue_feature(dic):
    """
    获取卓越类HR报告内容
    :param dic: 
    :return: 
    """
    url = 'http://%s:%d/application/hr?jstr=%s' % (OCEAN_IP, OCEAN_PORT, json.dumps(dic))
    log.info('后台接口: %s' % url)
    q = requests.get(url=url).content.decode()
    return q


def get_mix_allsurvey_feature(dic):
    """
    获取任何卷的特征的接口
    :param dic:
    :return:
    """
    url = 'http://%s:%d/application/feature?jstr=%s' % (OCEAN_IP, OCEAN_PORT, json.dumps(dic))
    log.info('后台接口: %s' % url)
    q = requests.get(url=url).content.decode()
    return q


def gen_email_url(guid):
    '''
    生成发送到HR email的邮件内容
    :param code: 
    :param name: 
    :param cellphone: 
    :param job: 
    :return: 
    '''
    # url = '%s?guid=%s' % (config.REPORT_HOST, guid)
    return None


class HRHandler(object):
    """
    HR
    """

    def _str_to_date(self, timestr):
        pass

    def get_report(self, code, guid, mode):
        log.info('保险经纪人获取报告记录的GUID为：%s' % guid)
        #
        # 保险经纪人根据用户名和手机号获取用户信息
        db, client = us.get_db_client()
        rows = db.responses_collection.find_one({'guid': guid, 'code': code})
        bigfive = rows['zocean']
        bigfive['mode'] = mode
        survey_item = db.surveys_collection.find_one({'code': code})
        # KafkaLogger().log_event(event='a_api', app='p_aggent', user=guid, level='info',
        #                         msg=str(code) + '保险经纪人获取报告记录',
        #                         status='200')
        total_score = None
        try:
            total_score = rows.get('get_feature').get('total_score')
        except Exception as e:
            print(str(e))
        if survey_item.get('survey_version') == 2:
            result = {'data': [], 'total_score': total_score}
            try:
                list = rows.get('feature_report').get('result')
                res = {}
                module_code1 = []
                module_code2 = []
                module_code3 = []
                module_code4 = []
                for ls in list:
                    modules = []
                    rule_id = ls.get('rule_id')
                    trait = db.t_rule_trait.find_one({'rule_id': rule_id})
                    if trait is not None:
                        module_code = trait.get('module_code')
                        score = ls.get('sim')
                        if 31 > score > 0:
                            ls['trait_detail'] = trait.get('score_sub').get('level_1')
                            trait['module_desc'] = ''
                            trait['module_title'] = ''
                        if 51 > score > 30:
                            ls['trait_detail'] = trait.get('score_sub').get('level_2')
                            trait['module_desc'] = ''
                            trait['module_title'] = ''
                        if 71 > score > 50:
                            ls['trait_detail'] = trait.get('score_sub').get('level_3')
                        if 101 > score > 70:
                            ls['trait_detail'] = trait.get('score_sub').get('level_4')
                        if 'score_sub' in trait:
                            del trait['score_sub']
                        if 'score_rang' in trait:
                            del trait['score_rang']
                        if 'rule_id' in trait:
                            del trait['rule_id']
                        if '_id' in trait:
                            del trait['_id']
                            demo = ls.copy()
                            demo.update(trait)
                        if demo is not None:
                            if res.get(module_code) is None:
                                res[module_code] = []
                            modules = demo
                            if str(module_code) == 'aim_demand':
                                module_code1.append(modules)
                            if str(module_code) == 'pro_info':
                                module_code2.append(modules)
                            if str(module_code) == 'fac_order':
                                module_code3.append(modules)
                            if str(module_code) == 'keep_touch':
                                module_code4.append(modules)
                if 'aim_demand' in res:
                    res['aim_demand'] = module_code1
                if 'pro_info' in res:
                    res['pro_info'] = module_code2
                if 'fac_order' in res:
                    res['fac_order'] = module_code3
                if 'keep_touch' in res:
                    res['keep_touch'] = module_code4
                result['data'] = res
                result['total_score'] = total_score
                result = json.dumps(result)
            except Exception as e:
                print(str(e))
        else:
            if mode is None or mode == 'zhuoyue':
                log.write_log(msg='获取卓越报告', event='view_report', product_id='bole')
                result = get_zhuoyue_feature(bigfive)
            else:
                result = get_hr_feature(bigfive)
        #
        # 必须拼接个人信息
        info = {}
        try:
            resp = rows.get('response')
            # 姓名: 571
            try:
                name = resp['571']['answer']
                info['name'] = name
            except Exception as e:
                pass
            try:
                contact = resp['575']['answer']
                info['contact'] = contact
            except Exception as e:
                pass
            try:
                job = resp['576']['answer']
                info['job'] = job  # 岗位
            except Exception as e:
                pass
            try:
                old = resp['572']['answer']
                info['old'] = old  # 年龄
            except Exception as e:
                pass
            try:
                sex = resp['814']['answer']
                info['sex'] = sex  # 性别
            except Exception as e:
                pass
            try:
                school = resp['1228']['answer']
                info['school'] = school  # 毕业院校
            except Exception as e:
                pass
            try:
                education = resp['1234']['answer']
                info['education'] = education  # 学历/学位
            except Exception as e:
                pass
            try:
                major = resp['1229']['answer']
                info['major'] = major  # 所学专业
            except Exception as e:
                pass
            try:
                info['last_date'] = rows.get('last_date')
                info['hr_status'] = resp['hr_status']
                info['note'] = resp['note']
            except Exception as e:
                pass
            # 计算答题时间
            start = time.mktime(time.strptime(resp['start'], '%Y%m%d%H%M%S'))
            end = time.mktime(time.strptime(resp['end'], '%Y%m%d%H%M%S'))
            time_cost = end - start
            info['time_cost'] = time_cost
            info['code'] = 200
        except Exception as e:
            log.error(e)
            info['code'] = 500
        info['data'] = json.loads(result)
        return json.dumps(info)

    def get(self, code, guid, mode):
        log.info('记录的GUID为：%s' % guid)
        #
        # 根据用户名和手机号获取用户信息
        #
        db, client = us.get_db_client()
        rows = db.responses_collection.find_one({'guid': guid, 'code': code})
        bigfive = rows['zocean']
        bigfive['mode'] = mode
        survey_item = db.surveys_collection.find_one({'code': code})

        #
        # 模型返回结果
        # 查询code,如果为其他问卷则使用mixall接口
        # score同sim
        # dim另外会加上去, subdim是卓越要求暂时不加
        # 出特征接口
        # input = '
        # {
        #     "personality": {"O": 0.5, "C": -0.7, "E": 0.6, "A": -0.8, "N": -0.55},
        #     "feature": [
        #         {"rule_id": "b1", "content": "hello", "weight": 0.5},
        #         {"rule_id": "b2", "content": "world", "weight": 0.5}
        #     ]
        # }
        # '
        #
        # output = '
        # {
        #     "total_score": 80,
        #     "score_list": [
        #         {"rule_id": "b1", "content": "hello", "score": 70},
        #         {"rule_id": "b2", "content": "world", "score": 90}
        #     ]
        # }
        # '
        total_score = None
        try:

            total_score = rows.get('get_feature').get('total_score')
        except Exception as e:
            print(str(e))
        if survey_item.get('survey_version') == 2:
            result = {'data': [], 'total_score': total_score}
            try:
                list = rows.get('feature_report').get('result')
                result['data'] = list
                result['total_score'] = total_score
                result = json.dumps(result)
            except Exception as e:
                print(str(e))
        else:
            if mode is None or mode == 'zhuoyue':
                log.write_log(msg='获取卓越报告', event='view_report', product_id='bole')
                result = get_zhuoyue_feature(bigfive)
            else:
                result = get_hr_feature(bigfive)
        #
        # 必须拼接个人信息
        info = {}
        try:
            resp = rows.get('response')
            # 姓名: 571
            try:
                name = resp['571']['answer']
                info['name'] = name
            except Exception as e:
                pass
            try:
                contact = resp['575']['answer']
                info['contact'] = contact
            except Exception as e:
                pass
            try:
                job = resp['576']['answer']
                info['job'] = job  # 岗位
            except Exception as e:
                pass
            try:
                old = resp['572']['answer']
                info['old'] = old  # 年龄
            except Exception as e:
                pass
            try:
                sex = resp['814']['answer']
                info['sex'] = sex  # 性别
            except Exception as e:
                pass
            try:
                school = resp['1228']['answer']
                info['school'] = school  # 毕业院校
            except Exception as e:
                pass
            try:
                education = resp['1234']['answer']
                info['education'] = education  # 学历/学位
            except Exception as e:
                pass
            try:
                major = resp['1229']['answer']
                info['major'] = major  # 所学专业
            except Exception as e:
                pass
            try:
                info['last_date'] = rows.get('last_date')
                info['hr_status'] = resp['hr_status']
                info['note'] = resp['note']
            except Exception as e:
                pass
            # 计算答题时间
            start = time.mktime(time.strptime(resp['start'], '%Y%m%d%H%M%S'))
            end = time.mktime(time.strptime(resp['end'], '%Y%m%d%H%M%S'))
            time_cost = end - start
            info['time_cost'] = time_cost
            info['code'] = 200
        except Exception as e:
            log.error(e)
            info['code'] = 500
        info['data'] = json.loads(result)
        return json.dumps(info)

    def addjob(self, job_cname, company_id, job_channel=None, percent=None, survey_code=None, max_limit=50,
               p_company_id=None):
        # survey_code 选定的问卷模板
        log.info('新增岗位job')
        #
        db, client = us.get_db_client()
        company = db.company_collection.find_one({'guid': company_id})  # pincn_ subcompany1
        if p_company_id is None:
            p_company_id = company.get('p_company_id')
        if p_company_id is None:
            p_company_id = company_id
        if job_channel is None:
            if p_company_id is None:
                p_company_id = company.get('guid')
            if p_company_id == 'zhongjin':
                job_channel = [0, 0, 1]
            else:
                job_channel = [1, 1, 1]
        # job_name = "".join(lazy_pinyin(job_cname, style=Style.NORMAL)).strip() + create_4random_pwd(codelen=6)
        # job_cname = job_cname.strip()
        job_cname = strq2b(job_cname)
        pjob_cname = ''.join(lazy_pinyin(job_cname, style=Style.NORMAL)).replace(' ', '') \
            .replace('\t', '').replace('?', '').replace('\r', '').replace('\n', '') \
            .replace('/', '').replace('\\', '').replace('\r', '').replace('\n', '') \
            .replace('#', '').replace('&', '').replace('_', '').replace('-', '')
        job_name = pjob_cname + create_4random_pwd(codelen=6)
        code = job_name
        percentlist = []
        for item in percent:
            if item.get('weight') == 0:
                pass
            else:
                percentlist.append(item)
        db.t_company_job.update(
            {'company_id': company_id, 'job_cname': job_cname}, {'$set': {'company_id': company_id,
                                                                          'p_company_id': p_company_id,
                                                                          'job_name': job_name,
                                                                          'job_cname': job_cname,
                                                                          'percent': percentlist,
                                                                          'job_channel': job_channel,
                                                                          'code': code,
                                                                          'create_date': time.strftime(
                                                                              '%Y-%m-%d %H:%M:%S',
                                                                              time.localtime(
                                                                                  time.time())), }
                                                                 }, upsert=True)

        info = deepcopy(g_ret)
        from module_questions.customer_combine import cc_insert4newcompany
        param1 = {'p_company_id': p_company_id, 'company_id': company_id, 'token': 'tokenhuayuanapi',
                  'code': code, 'job_cname': job_cname, 'job_name': job_name, 'select_survey_code': survey_code}
        cc_insert4newcompany(param1=param1)
        db.t_user_limit.update(
            # {'code': code}, {'$set': {'cur_times': 0,  # 改为企业id存储
            #                           'max_limit': max_limit,
            #                           'code': code,
            #                           'company_id': company_id
            #                           }},
            {'code': code}, {'$set': {'cur_times': 0,
                                      'max_limit': max_limit,
                                      'code': code,
                                      'p_company_id': p_company_id,
                                      'company_id': company_id}},
            upsert=True
        )
        # TODO 公司 zhongjin 下企业修改问卷问题，增加岗位所在地题号
        surveys = db.surveys_collection.find_one({'code': code, 'company_id': company_id})
        if surveys is not None and company_id == 'zhongjin':
            questions = surveys.get('questions')
            questions_list = questions.split(',')
            ques = []
            for q in questions_list:
                ques.append(q)
                if q == '576':
                    ques.append('1383')
            ques_str = ','.join(ques)
            db.surveys_collection.update(
                {'code': code, 'company_id': company_id},
                {'$set': {'questions': ques_str}},
                upsert=False
            )
        info['code'] = 200
        info['survey_code'] = code
        return info

    def jobdetail(self, company_id, job_cname):
        log.info('查询job明细和问卷信息')
        #
        db, client = us.get_db_client()
        info = deepcopy(g_ret)
        job_cname = job_cname.strip()
        if job_cname == '默认':
            info['code'] = 200
            info['total_count'] = 0
            return json.dumps(info)
        try:
            job_row = db.t_company_job.find_one({'company_id': company_id, 'job_cname': job_cname})
            if job_row is not None:
                surve_row = db.surveys_collection.find_one({'company_id': company_id, 'code': job_row.get('code')})
            else:
                surve_row = None
            if job_row is not None:
                if '_id' in job_row:
                    del job_row['_id']
            if surve_row is not None:
                if '_id' in surve_row:
                    del surve_row['_id']
            info['code'] = 200
            info['survey'] = surve_row
            info['job'] = job_row
            info['total_count'] = 1
            if job_row is None:
                info['total_count'] = 0
        except Exception as e:
            print(str(e))
            info['code'] = 200
            info['total_count'] = 0
        return json.dumps(info)

    def check_deadline(self, code):
        """
            检查当前code的截止日期是否在有效期
         :return:
        """
        log.info('检查问卷是否被禁止使用, code: %s' % code)
        db, client = us.get_db_client()
        ret = db.t_user_limit.find_one({'code': code})
        if ret is not None:
            log.info('开始查询截止日期')
            deadLine = ret.get('dead_line')
            nowTime_str = datetime.datetime.now().strftime('%Y-%m-%d')
            if deadLine is not None:
                try:
                    e_time = time.mktime(time.strptime(nowTime_str, "%Y-%m-%d"))
                    s_time = time.mktime(time.strptime(deadLine, '%Y-%m-%d'))
                    diff = int(s_time) - int(e_time)
                    log.debug('截止日期小于当前时间')
                    print(diff)
                    if diff >= 0:
                        return True
                    else:
                        log.debug('截止日期小于当前时间')
                        print('所查日期不能小于当前时间！！！')
                        return False
                except Exception as e:
                    log.debug('截止日期判断异常: %s' % e)
                    print(e)
                    return False
        return False

    def jobdetailbycode(self, company_id, code):
        log.info('查询job明细和问卷信息')
        #
        db, client = us.get_db_client()
        info = deepcopy(g_ret)
        try:
            job_row = db.t_company_job.find_one({'company_id': company_id, 'code': code})
            if job_row is not None:
                surve_row = db.surveys_collection.find_one({'company_id': company_id, 'code': job_row.get('code')})
            else:
                surve_row = None
            if job_row is not None:
                if '_id' in job_row:
                    del job_row['_id']
            if surve_row is not None:
                if '_id' in surve_row:
                    del surve_row['_id']
            info['code'] = 200
            # info['survey'] = surve_row
            # info['job'] = job_row
            info['total_count'] = 1
            if job_row is None:
                info['total_count'] = 0
        except Exception as e:
            print(str(e))
            info['code'] = 200
            info['total_count'] = 0
        info['count'] = info['total_count']
        return json.dumps(info)

    def joblist(self, company_id, page=1, pagesize=500):
        log.info('查询job列表')
        #
        db, client = us.get_db_client()
        rows = db.t_company_job.find({'company_id': company_id}).sort(
            [('create_date', pymongo.DESCENDING), ('job_cname', pymongo.ASCENDING)]).skip(
            (page - 1) * pagesize).limit(pagesize)
        info = deepcopy(g_ret)
        info['code'] = 200
        list = rows2list(rows)
        for item in list:
            print(item)
            user_pv = db['responses_collection'].find({'code': item['code']}).count()
            item['total'] = user_pv
        info['data'] = list
        info['total_count'] = db.t_company_job.find({'company_id': company_id}).count()
        info['count'] = info['total_count']
        info['page'] = page
        info['pagesize'] = pagesize
        return json.dumps(info)

    def upjobstatus(self, company_id, code, job_status):
        log.info('更新job岗位问卷使用状态，0为正常使用，1为禁止使用')
        #
        db, client = us.get_db_client()
        info = deepcopy(g_ret)
        try:
            db.t_company_job.update({'company_id': company_id, 'code': code},
                                    {'$set': {'job_status': int(job_status)}}, upsert=True)
            info['code'] = 200
        except Exception as e:
            print(str(e))
        return json.dumps(info)

    def deljob(self, company_id, job_cname):
        log.info('删除job')
        #
        db, client = us.get_db_client()
        info = deepcopy(g_ret)
        try:
            job_item = db.t_company_job.find_one({'company_id': company_id, 'job_cname': job_cname})
            rows = db.t_company_job.remove({'company_id': company_id, 'job_cname': job_cname})
            db.surveys_collection.update({'company_id': job_item['company_id'], 'code': job_item['code']},
                                         {'$set': {'company_id': 'delflag_' + job_item['company_id']}})
            info['code'] = 200
        except Exception as e:
            print(str(e))
        return json.dumps(info)

    def rulelist(self, company_id, page=1, pagesize=100):
        log.info('查看特征列表')
        #
        db, client = us.get_db_client()
        info = deepcopy(g_ret)
        info['code'] = 200
        rows = db.t_selectrule_map.find({'company_id': company_id})
        rulelist = []
        if rows.count() > 0:
            rulelist = rows2list(rows)
        else:
            rows = db.t_selectrule_map.find({'company_id': 'default_all'})
            print(rows.count())
            rulelist = rows2list(rows)
        for item in rulelist:
            item['weight'] = 0
        info['data'] = rulelist
        return json.dumps(info)

    def getlimit(self, p_company_id):
        log.info('查询公司和子公司限制次数')
        #
        db, client = us.get_db_client()
        info = deepcopy(g_ret)
        info['code'] = 200
        total_max_limit = 0
        total_cur_times = 0
        rowslist = []
        limitlist = []
        rows = db.surveys_collection.find({'$or': [{'company_id': p_company_id}, {'p_company_id': p_company_id}]})
        if rows.count() > 0:
            rowslist = rows2list(rows)
        for item in rowslist:
            company_id = item.get('company_id')
            code = item.get('code')
            row = db.t_user_limit.find_one({'code': code})
            if row is not None:
                if row.get('max_limit') is not None and row.get('cur_times') is not None:
                    total_max_limit = total_max_limit + int(row['max_limit'])
                    total_cur_times = total_cur_times + int(row['cur_times'])
                    limitlist.append({'code': code, 'company_id': company_id, 'max_limit': row.get('max_limit'),
                                      'cur_times': row.get('cur_times')})
        info['data'] = limitlist
        info['total_max_limit'] = total_max_limit
        info['total_cur_times'] = total_cur_times
        return json.dumps(info)

    def getbole_limit(self, company_id):
        log.info('查询bole用户本公司限制次数')
        #
        db, client = us.get_db_client()
        info = deepcopy(g_ret)
        info['code'] = 200
        # ret = db.t_user_limit.find_one({'code': code})
        # if ret is None:
        #     # 数据库中无限制记录，认为无限制
        #     info['total_max_limit'] = 100000
        #     info['total_cur_times'] = 0
        #     json.dumps(info)
        #
        # cur_times = ret['cur_times']
        # # max_times = ret['max_limit']
        # if ret is not None:
        #     print(ret['company_id'])
        #     company_id = ret.get('company_id')
        ret_max = db.t_user_limit.find_one({'company_id': company_id}, sort=[('max_limit', -1)])
        max_limit = None
        cur_total_times = 0
        if ret_max is not None:
            print(ret_max.get('max_limit'))
            max_limit = ret_max.get('max_limit')
            if max_limit is None:
                return True
        sum = db.t_user_limit.aggregate([
            {"$match": {"company_id": company_id}},
            {"$group": {"_id": "$company_id", "all_count": {"$sum": "$cur_times"}}}
        ])
        for sumone in sum:
            print(sumone.get('all_count'))
            cur_total_times = sumone.get('all_count')
        info['total_max_limit'] = max_limit
        info['total_cur_times'] = cur_total_times
        return json.dumps(info)

    def addjobmaxlimit(self, company_id, code, addlimit, appkey):
        appkey = str(appkey)
        error_ret = deepcopy(g_ret)
        if appkey in APP_KEY_LIST:
            ret = db.t_user_limit.find_one({'code': code})
            if ret is not None:
                max_times = ret['max_limit']
                cur_times = ret['cur_times']
                db.t_user_limit.update(
                    {'code': code}, {'$set': {
                        'max_limit': max_times + int(addlimit),
                        'code': code, 'company_id': company_id
                    }},
                    upsert=True
                )
            error_ret['msg'] = 'ok'
            error_ret['code'] = 200
            error_ret['max_limit'] = max_times + int(addlimit)
            error_ret['cur_times'] = cur_times
            error_ret['company_id'] = company_id
            error_ret['survey_code'] = code
            return json.dumps(error_ret)
        else:
            error_ret['msg'] = 'appkey fail'
            error_ret['code'] = 401
            return json.dumps(error_ret)

    def daymaxlimit_api(self, company_id, code, addlimit, appkey):
        appkey = str(appkey)
        error_ret = deepcopy(g_ret)
        if appkey in APP_KEY_LIST:
            ret = db.t_user_limit.find_one({'code': code})
            if ret is not None:
                day_times = ret['day_limit']
                if day_times is None or day_times == '':
                    day_times = 0
                db.t_user_limit.update(
                    {'code': code}, {'$set': {
                        'day_limit': day_times + int(addlimit),
                        'code': code, 'company_id': company_id
                    }},
                    upsert=True
                )
            error_ret['msg'] = 'ok'
            error_ret['code'] = 200
            error_ret['day_limit'] = day_times + int(addlimit)
            error_ret['company_id'] = company_id
            error_ret['survey_code'] = code
            return json.dumps(error_ret)
        else:
            error_ret['msg'] = 'appkey fail'
            error_ret['code'] = 401
            return json.dumps(error_ret)

    def query_bxjjr_qr(self, user_id, product='insure'):
        error_ret = deepcopy(g_ret)
        shorturl = None
        ret_company = db.t_user_product.find_one({'user_id': user_id, 'product_id': product}, sort=[('user_id', -1)])
        if ret_company is not None:
            company_id = ret_company.get('company_id')
        else:
            error_ret['msg'] = 'company is null for user_product'
            return error_ret
        ret_survey = db.surveys_collection.find_one({'company_id': company_id}, sort=[('create_time', 1)])
        if ret_survey is not None:
            shorturl = ret_survey.get('shorturl')
        else:
            error_ret['msg'] = 'ret_survey is null'
            return error_ret
        if shorturl is not None:
            error_ret['shorturl'] = shorturl + '__0_' + user_id  # __clientid_groupid
            error_ret['nowx_shorturl'] = shorturl + '_nowx__0_' + user_id  # __clientid_groupid
            error_ret['msg'] = 'ok'
            error_ret['msg_flag'] = 'ok'
            error_ret['code'] = 200
            return json.dumps(error_ret)
        else:
            error_ret['msg'] = 'fail'
            error_ret['code'] = 401
            return json.dumps(error_ret)


hrHandler = HRHandler()


def rows2list(rows):
    list = []
    for item in rows:
        if '_id' in item:
            del item['_id']
        list.append(item)
    return list


@app.route('/hr/<code>/<guid>/<mode>', methods=['GET', 'POST'])
def get_hr_report(code, guid, mode):
    # 获取报告
    log.debug('get hr report ')
    hr_handler = HRHandler()
    return hr_handler.get(code, guid, mode)


@app.route('/insure/<code>/<guid>/<mode>', methods=['GET', 'POST'])
def get_insure_report(code, guid, mode):
    # 针对保险经纪人，增加报告推荐内容获取报告
    log.debug('get hr report ')
    hr_handler = HRHandler()
    return hr_handler.get_report(code, guid, mode)


@app.route('/hr/<code>/<guid>', methods=['GET', 'POST'])
def get_zhuoyue_report(code, guid):
    log.debug('get zhuoyue report ')
    hr_handler = HRHandler()
    return hr_handler.get(code, guid, None)


@app.route('/hrzj/addjob', methods=['GET', 'POST'])
# @verify_token
def hrzj_addjob():
    '''
    添加岗位
    '''
    log.debug('添加岗位')
    param = get_param(request)
    return json.dumps(hrHandler.addjob(job_cname=param.get('job_cname'),
                                       company_id=param.get('company_id'),
                                       job_channel=param.get('job_channel'),
                                       percent=param.get('percent'),
                                       survey_code=param.get('survey_code')
                                       )
                      )


@app.route('/insure/check_deadLine', methods=['GET', 'POST'])
def get_check_deadLine():
    log.debug('判断截止日期！')
    param = get_param(request)
    code = str(param.get('code'))
    ret = deepcopy(g_ret)
    # KafkaLogger().log_event(event='a_api', app='p_aggent', user=code, level='info', msg=str(code) + '判断截止日期',
    #                         status='200')
    if not hrHandler.check_deadline(code):
        ret['code'] = 400
        ret['msg'] = '超过截止日期!'
    else:
        ret['code'] = 200
        ret['msg'] = '有效期范围内！'
    return json.dumps(ret)


@app.route('/hrzj/addjobapi', methods=['GET', 'POST'])
# @verify_token
def hrzj_addjobapi():
    '''
    添加岗位
    '''
    log.debug('添加岗位')
    param = get_param(request)
    appkey = str(param.get('appkey'))
    f_company_id = None
    error_ret = deepcopy(g_ret)
    if appkey in APP_KEY_LIST:
        f_company_id = appkey.split('_')[0]
    else:
        error_ret['msg'] = 'appkey fail'
        error_ret['code'] = 401
        return json.dumps(error_ret)
    return json.dumps(hrHandler.addjob(job_cname=param.get('job_cname'),
                                       company_id=param.get('company_id'),
                                       job_channel=param.get('job_channel'),
                                       percent=param.get('percent'),
                                       survey_code=param.get('survey_code'),
                                       max_limit=int(param.get('max_limit'))
                                       )
                      )


@app.route('/hrzj/jobdetail', methods=['GET', 'POST'])
# @verify_token
def hrzj_jobdetail():
    '''
    查看岗位详情
    '''
    log.debug('查看岗位详情及其二维码问卷')
    param = get_param(request)
    company_id = param.get('company_id')
    job_cname = param.get('job_cname')
    return hrHandler.jobdetail(company_id, job_cname)


@app.route('/hrzj/jobcodedetail', methods=['GET', 'POST'])
# @verify_token
def hrzj_jobcodedetail():
    '''
    查看岗位详情
    '''
    log.debug('查看岗位详情及其二维码问卷by code')
    param = get_param(request)
    company_id = param.get('company_id')
    code = param.get('code')
    return hrHandler.jobdetailbycode(company_id, code)


@app.route('/hrzj/rulelist', methods=['GET', 'POST'])
# @verify_token
def hrzj_rulelist():
    '''
    查询特征列表
    '''
    log.debug('查询特征列表')
    param = get_param(request)
    company_id = param.get('company_id')
    return hrHandler.rulelist(company_id)


@app.route('/hrzj/deljob', methods=['GET', 'POST'])
# @verify_token
def hrzj_deljob():
    '''
    删除岗位,相关问卷不再查询,岗位设置状态status=-1
    '''
    log.debug('删除岗位')
    param = get_param(request)
    # g_user_id, ret = check_token(param.get('token'))
    company_id = param.get('company_id')
    job_cname = param.get('job_cname')
    return hrHandler.deljob(company_id, job_cname)


@app.route('/hrzj/upjobstatus', methods=['GET', 'POST'])
# @verify_token
def hrzj_upjobstatus():
    '''
     更新岗位状态，控制问卷的使用状态，0是可以使用，1是禁止使用
    '''
    log.debug('更改岗位问卷使用状态为禁用')
    param = get_param(request)
    # g_user_id, ret = check_token(param.get('token'))
    company_id = param.get('company_id')
    job_status = param.get('job_status')
    code = param.get('code')
    return hrHandler.upjobstatus(company_id, code, job_status)


@app.route('/hrzj/joblist', methods=['GET', 'POST'])
# @verify_token
def hrzj_joblist():
    '''
    查询岗位列表及其问卷二维码
    '''
    log.debug('查询岗位列表')
    param = get_param(request)
    company_id = param.get('company_id')
    if param.get('page') is None:
        page = 1
    else:
        page = int(param.get('page'))
    if param.get('pagesize') is None:
        pagesize = 500
    else:
        pagesize = int(param.get('pagesize'))
    return hrHandler.joblist(company_id, page=page, pagesize=pagesize)


@app.route('/hrzj/getbole_limit', methods=['GET', 'POST'])
@verify_token
def hrzj_getbole_limit():
    '''
    查询公司子公司次数限制
    '''
    log.debug('查询bole本公司次数限制')
    param = get_param(request)
    company_id = param.get('company_id')
    # KafkaLogger().log_event(event='a_api', app='p_aggent', user=param.get('user_id'), level='info', msg=str(company_id) + '查询公司子公司次数限制',
    #                         status='200')
    return hrHandler.getbole_limit(company_id=company_id)


@app.route('/hrzj/getlimitapi', methods=['GET', 'POST'])
# @verify_token
def hrzj_getlimitapi():
    '''
    查询公司子公司次数限制
    '''
    log.debug('查询公司子公司次数限制')
    param = get_param(request)
    company_id = param.get('company_id')
    return hrHandler.getlimit(p_company_id=company_id)


@app.route('/hrzj/addjobmaxlimit_api', methods=['GET', 'POST'])
# @verify_token
def hrzj_addjobmaxlimit_api():
    '''
    设置公司子公司次数限制
    '''
    log.debug('设置公司子公司次数限制')
    param = get_param(request)
    appkey = param.get('appkey')
    code = param.get('code')
    addlimit = param.get('addlimit')
    return hrHandler.addjobmaxlimit(code=code, addlimit=addlimit, appkey=appkey)


@app.route('/insure/daymaxlimit_api', methods=['GET', 'POST'])
@verify_token
def insure_daymaxlimit_api():
    '''
    设置非会员保险经纪人当天使用次数限制
    '''
    log.debug('设置保险经纪人当天使用次数限制')
    param = get_param(request)
    appkey = param.get('appkey')
    code = param.get('code')
    addlimit = param.get('addlimit')
    return hrHandler.daymaxlimit_api(code=code, addlimit=addlimit, appkey=appkey)


@app.route('/hrzj/query_bxjjr_qr', methods=['GET', 'POST'])
@verify_token
def query_bxjjr_qr():
    '''
    查询长短链接
    '''
    log.debug('查询长短链接')
    param = get_param(request)
    g_user_id, ret = check_token(param.get('token'))

    if g_user_id is None:
        return ret
    # KafkaLogger().log_event(event='a_api', app='p_aggent', user=g_user_id, level='info', msg=str(g_user_id) + '获取短连接',
    #                         status='200')
    return hrHandler.query_bxjjr_qr(user_id=g_user_id)


# @app.route('/hrzj/newcompany', methods=['GET', 'POST'])
# @verify_token
# def hrzj_newcompany():
#     '''
#     新增用户公司,父公司为自己或zhongjin Pincn
#     '''
#     log.debug('新增用户公司')
#     param = get_param(request)
#     g_user_id, ret = check_token(param.get('token'))
#     if g_user_id is None:
#         return ret
#     return json.dumps(hrHandler.get(1, 1, 1))


# @app.route('/hrzj/getreportlist', methods=['GET', 'POST'])
# @verify_token
# def hrzj_getreportlist():
#     '''
#     查询报告列表,排除删除的岗位
#     '''
#     log.debug('查询报告列表,排除删除的岗位')
#     param = get_param(request)
#     g_user_id, ret = check_token(param.get('token'))
#     if g_user_id is None:
#         return ret
#     return json.dumps(hrHandler.get(1, 1, 1))


# @app.route('/hrzj/getreportdetail', methods=['GET', 'POST'])
# @verify_token
# def hrzj_getreportdetail():
#     '''
#     查询单个报告明细
#     '''
#     log.debug('查询单个报告明细')
#     param = get_param(request)
#     g_user_id, ret = check_token(param.get('token'))
#     if g_user_id is None:
#         return ret
#     return json.dumps(hrHandler.get(1, 1, 1))


def strq2b(ustring):
    """全角转半角"""
    rstring = ""
    for uchar in ustring:
        inside_code = ord(uchar)
        if inside_code == 12288:  # 全角空格直接转换
            inside_code = 32
        elif (inside_code >= 65281 and inside_code <= 65374):  # 全角字符（除空格）根据关系转化
            inside_code -= 65248

        rstring += chr(inside_code)
    return rstring


def strb2q(ustring):
    """半角转全角"""
    rstring = ""
    for uchar in ustring:
        inside_code = ord(uchar)
        if inside_code == 32:  # 半角空格直接转化
            inside_code = 12288
        elif inside_code >= 32 and inside_code <= 126:  # 半角字符（除空格）根据关系转化
            inside_code += 65248

        rstring += chr(inside_code)
    return rstring


if __name__ == '__main__':
    # params = {'O':1.2, 'C':2.1, 'E': 0.9, 'A': 1.1, 'N':-1.3}
    #
    # ret = get_zhuoyue_feature(params)
    # print(ret)
    # db, client = us.get_db_client()
    #
    # ret = {
    #     'user_id': 'wenyi.hua',
    #     'max_limit': 10,
    #     'cur_times': 0
    # }
    # db.t_user_limit.insert(ret)
    job_cname = ' 投资顾问（IC）'
    job_cname = strq2b(job_cname)
    print(job_cname)
    job_cname = ''.join(lazy_pinyin(job_cname, style=Style.NORMAL)).replace(' ', '') \
        .replace('\t', '').replace('?', '').replace('\r', '').replace('\n', '') \
        .replace('/', '').replace('\\', '').replace('\r', '').replace('\n', '') \
        .replace('#', '').replace('&', '').replace('_', '').replace('-', '')
    job_name = job_cname + create_4random_pwd(codelen=6)
    code = job_name
    print(job_cname)
    print(job_name)
